package cn.myfirefly.moming.common.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import cn.myfirefly.moming.common.dao.DataDictItemDao;
import cn.myfirefly.moming.common.entity.MMDataDict;
import cn.myfirefly.moming.common.model.DataDictDto;
import cn.myfirefly.moming.common.model.DataDictFilterDto;
import cn.myfirefly.core.Const;
import cn.myfirefly.core.model.PageResultDto;
import cn.myfirefly.utils.BeanUtil;
import cn.myfirefly.utils.StrUtil;

@Service
@Transactional
public class DataDictItemService {
	
	@Autowired
	DataDictItemDao dataDictItemDao;

	public PageResultDto<MMDataDict> getList(DataDictFilterDto dto, String dataTypeItem) {
		
		return dataDictItemDao.getList(dto,dataTypeItem);
	}
	public String save(DataDictDto dto) {
		MMDataDict dataDict = null;
		// 更新
		if (StrUtil.notBlank(dto.getDataDictSn())) {
			dataDict = dataDictItemDao.get(dto.getDataDictSn());
			if (dataDict != null && !dataDict.getDataDictSn().equals(dto.getDataDictSn())) {
				return "数据项已存在";
			}
		} else {
		// 新增
			dataDict = new MMDataDict();
			dataDict.setCreateBy(dto.getModifyBy());
			dataDict.setCreateDate(dto.getModifyDate());
		}
		BeanUtil.copyBeans(dto, dataDict);
		dataDictItemDao.save(dataDict);
		return Const.ResultCode.SUCCESS;
	}
	
	public DataDictDto getDataDict(Integer dataDictSn) {
		MMDataDict dataDict = dataDictItemDao.get(dataDictSn);
		return BeanUtil.copyBeans(DataDictDto.class, dataDict);
	}
	
	public String del(DataDictDto dto) {
		MMDataDict dataDict = dataDictItemDao.get(dto.getDataDictSn());
		if (dataDict == null) {
			return "数据项信息不存在，请刷新页面后重试";
		}
		if (dataDict != null && !dataDict.getDataDictSn().equals(dto.getDataDictSn())) {
			return "数据项信息已变更，请刷新页面后重试";
		}
		//通过类型查询 如果只有�?条数据项 不能进行删除操作
		long count = dataDictItemDao.countByDataType(dto.getDataType());
		if(count <= 1 ){
			return "数据项至少存在一条";
		}
		
		dataDictItemDao.del(dataDict);
		return Const.ResultCode.SUCCESS;
	}
}
